import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/widget/tab_layout_widget.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/punch_in_rule_list_widget.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/set_rule/set_punch_in_rule_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'bean/punch_in_rule_bean.dart';

///考勤规则主页面
class PunchInRuleMainPage extends StatefulWidget {
  static const String ROUTER = "PunchInRuleMainPage";

  static Future<Map> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult<Map>(
      context,
      PunchInRuleMainPage(),
      routeName: PunchInRuleMainPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return PunchInRuleMainPageState();
  }
}

class PunchInRuleMainPageState extends BaseState with TickerProviderStateMixin {
  TabController _tabController;
  int staffCnt = 0;
  int stuCnt = 0;
  ValueNotifier<int> classOrDepartmentCntNotifier;

  @override
  void initState() {
    super.initState();
    classOrDepartmentCntNotifier = ValueNotifier(0);
    _tabController = TabController(length: canShowStu() ? 2 : 1, vsync: this);
    _tabController.addListener(() {
      if (_tabController.index == 0) {
        SharePreferenceUtil.getInt(KEY_DEPARTMENT_CNT +
                    UserRepository.getInstance().getCompanyId() ??
                '')
            .then((value) {
          print('部门数$value');
          classOrDepartmentCntNotifier.value = value;
        });
      } else {
        SharePreferenceUtil.getInt(
                KEY_CLASS_CNT + UserRepository.getInstance().getCompanyId() ??
                    '')
            .then((value) => classOrDepartmentCntNotifier.value = value);
      }
    });
    SharePreferenceUtil.getInt(
            KEY_DEPARTMENT_CNT + UserRepository.getInstance().getCompanyId() ??
                '')
        .then((value) {
      print('部门数$value');
      classOrDepartmentCntNotifier.value = value;
    });
  }

  bool canShowStu() => false;

  @override
  Widget build(BuildContext context) {
    List<Widget> tabs = <Widget>[
      _tabWidget('员工', staffCnt ?? 0),
    ];
    if (canShowStu()) {
      tabs.add(_tabWidget('学员', stuCnt ?? 0));
    }
    List<Widget> _tabViews = <Widget>[
      PunchInRuleListWidget(
        type: PunchInRuleListWidget.TYPE_STAFF,
        cntCallback: (cnt) {
          staffCnt = cnt;
          setState(() {});
        },
      ),
    ];
    if (canShowStu()) {
      _tabViews.add(PunchInRuleListWidget(
        type: PunchInRuleListWidget.TYPE_STU,
        cntCallback: (cnt) {
          stuCnt = cnt;
          setState(() {});
        },
      ));
    }
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        body: Container(
          child: Column(
            children: <Widget>[
              _toTopBarWidget(),
              Visibility(
                visible: canShowStu(),
                child: Container(
                  height: 45,
                  width: double.infinity,
                  alignment: Alignment.center,
                  color: Color(0xff191e31),
                  child: TabBar(
                    controller: _tabController,
                    isScrollable: true,
                    indicatorSize: TabBarIndicatorSize.label,
                    unselectedLabelStyle: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextMainColor_D0E0F7(),
                        fontSize: 15,
                        height: 1.2),
                    labelStyle: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextMinorGreyColor_808388(),
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        height: 1.2),
                    labelPadding: EdgeInsets.only(left: 50, right: 50),
                    indicatorColor:
                        ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    indicatorPadding: EdgeInsets.only(left: 3, right: 28),
                    tabs: tabs,
                  ),
                ),
              ),
              Expanded(
                child: ScrollConfiguration(
                  behavior: MyBehavior(),
                  child: TabBarView(
                    controller: _tabController,
                    children: _tabViews,
                  ),
                ),
              ),
              buildAddRuleBar(context)
            ],
          ),
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
    );
  }

  buildAddRuleBar(BuildContext context) {
    return ValueListenableBuilder<int>(
        valueListenable: classOrDepartmentCntNotifier,
        builder: (BuildContext context, int cnt, widget) {
          return Visibility(
            visible: (cnt ?? 0) > 0,
            child: GestureDetector(
              onTap: () async {
                bool result = await SetPunchInRulePage.navigatorPush(
                    context,
                    _tabController.index == 0
                        ? PunchInRuleListWidget.TYPE_STAFF
                        : PunchInRuleListWidget.TYPE_STU,
                    false,
                    PunchInRuleBean(
                        PunchInRuleType.custom,
                        _tabController.index == 0
                            ? PunchInRuleListWidget.TYPE_STAFF
                            : PunchInRuleListWidget.TYPE_STU));
                if (result != null && result) {}
              },
              child: Container(
                height: 52,
                padding: EdgeInsets.symmetric(horizontal: 15),
                color:
                    ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                child: Row(
                  children: [
                    Container(
                      width: 17,
                      height: 17,
                      margin: EdgeInsets.only(right: 6),
                      child: Image.asset(
                        "images/add_icon.png",
                        color: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF(),
                      ),
                    ),
                    Text(
                      '个性化规则',
                      style: TextStyle(
                          fontSize: 15,
                          color: ThemeRepository.getInstance()
                              .getTextMainColor_D0E0F7()),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      centerWidget: Column(
        children: <Widget>[
          Text(
            '考勤规则',
            style: TextStyle(
                fontSize: 17, color: Colors.white, fontWeight: FontWeight.bold),
          ),
          Container(
            width: 80,
            child: Text(
              UserRepository.getInstance().userData.companyInfo.companynick ??
                  UserRepository.getInstance()
                      .userData
                      .companyInfo
                      .companyname ??
                  "",
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 10,
                  color: Colors.white,
                  fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }

  _tabWidget(String tab, int cnt) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 5.0),
      child: Row(
        children: <Widget>[
          Text(tab),
          SizedBox(
            width: 3,
          ),
          Container(
            width: 24,
            child: Text(
              "${cnt ?? 0}",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 12,
              ),
            ),
          )
        ],
      ),
    );
  }
}
